//
//  KAChartViewController.m
//  KeepAccount
//
//  Created by Veer on 2017/12/21.
//  Copyright © 2017年 Veer. All rights reserved.
//

#import "KAChartViewController.h"

#import "XDropMenuView.h"
#import "KAChartCell.h"
#import "YAYIOALineChart.h"
#import "KAChartModel.h"
#import "KAAccountGroupModel.h"
#import "VRCalendarTool.h"


@interface KAChartViewController () <XDropMenuViewDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITextField *testTF;
@property (nonatomic, weak) YAYIOALineChart *chartView;
@property (nonatomic, weak) UITableView *tableView;

@property (nonatomic, weak) UISegmentedControl *segmentedControl;
@property (nonatomic, weak) UILabel *calendarTypeLbl;
@property (nonatomic, weak) UILabel *totalMoneyLbl;
@property (nonatomic, weak) UILabel *averageMoneyLbl;
@property (nonatomic, weak) UILabel *typeTitleLbl;


@property (nonatomic, strong) NSMutableArray<KAChartModel *> *chartModelArray;
@property (nonatomic, strong) NSMutableArray<KAAccountGroupModel *> *groupModelArray;

@property (nonatomic, assign) DataType dateType;
@property (nonatomic, assign) int type;

@end

@implementation KAChartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];

    [self setupTopView];
    [self setupSubView];
    [self setupDropMenu];
    [self setupHeaderView];
    
    NSDate *firstDate = [VRCalendarTool dateForFistDayOnWeek:[NSDate date]];
    NSDate *lastDate = [VRCalendarTool dateForLastDayOnWeek:[NSDate date]];
    NSString *firstDateStr = [VRCalendarTool stringWithDate:firstDate formatString:@"MM-dd"];
    NSString *lastDateStr = [VRCalendarTool stringWithDate:lastDate formatString:@"MM-dd"];
//
//    self.dateType = DataTypeThisWeek;
//    self.chartView.xArray = @[firstDateStr, lastDateStr];
//    self.chartView.chartType = ChartTypeThisWeek;
//    [self getData];
    [self indexDidChangeForSegmentedControl:self.segmentedControl];
    
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:kAddAccountNotificationName object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kAddAccountNotificationName object:nil];
}


- (void)setupTopView
{
    
    UIView *topView = [[UIView alloc] init];
    topView.backgroundColor = NAVColor;
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(NAVIGATION_BAR_HEIGHT);
        make.height.mas_equalTo(40);
    }];
    
    NSArray *segmentedArray = @[@"周", @"月", @"年"];
    
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedArray];
    segmentedControl.selectedSegmentIndex = 0;
    segmentedControl.tintColor = RGB(51, 51, 51);
    
    [segmentedControl addTarget:self action:@selector(indexDidChangeForSegmentedControl:) forControlEvents:UIControlEventValueChanged];
    [topView addSubview:segmentedControl];
    self.segmentedControl = segmentedControl;
    [segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
        make.height.mas_equalTo(30);
    }];
}


- (void)setupSubView
{
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    tableView.backgroundColor = [UIColor whiteColor];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tableHeaderView = [[UIView alloc] init];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.estimatedRowHeight = 0;
    tableView.estimatedSectionHeaderHeight = 0;
    tableView.estimatedSectionFooterHeight = 0;
    tableView.sectionHeaderHeight = 0;
    tableView.sectionFooterHeight = 0.01;
    tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, CGFLOAT_MIN)];
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, CGFLOAT_MIN)];
    tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    [self.view addSubview:tableView];
    self.tableView = tableView;
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(NAVIGATION_BAR_HEIGHT + 40);
    }];
}


- (void)setupHeaderView
{
    
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, kScreenWidth, 98 + 140 + 32);
    
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = @"本周";
    titleLbl.font = VRFont(18);
    titleLbl.textColor = RGB(51, 51, 51);
    [headerView addSubview:titleLbl];
    self.calendarTypeLbl = titleLbl;
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(15);
        make.height.mas_equalTo(35);
    }];
    
    // 线
    UIView *indicatorView = [[UIView alloc] init];
    indicatorView.backgroundColor = RGB(51, 51, 51);
    [headerView addSubview:indicatorView];
    [indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(titleLbl);
        make.centerX.mas_equalTo(titleLbl);
        make.width.mas_equalTo(38);
        make.height.mas_equalTo(1.5);
    }];
    
    // 线
    UIView *hLineView = [[UIView alloc] init];
    hLineView.backgroundColor = RGB(225, 225, 225);
    [headerView addSubview:hLineView];
    [hLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(titleLbl.mas_bottom);
        make.left.right.mas_equalTo(headerView);
        make.height.mas_equalTo(0.5);
    }];
    
    UILabel *totalMoneyLbl = [[UILabel alloc] init];
    totalMoneyLbl.text = @"总支出：40.00";
    totalMoneyLbl.font = VRFont(14);
    totalMoneyLbl.textColor = RGB(108, 108, 108);
    [headerView addSubview:totalMoneyLbl];
    self.totalMoneyLbl = totalMoneyLbl;
    [totalMoneyLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(hLineView).offset(14);
        make.left.mas_equalTo(15);
    }];
    
    UILabel *averageMoneyLbl = [[UILabel alloc] init];
    averageMoneyLbl.text = @"平均值：3.33";
    averageMoneyLbl.font = VRFont(12);
    averageMoneyLbl.textColor = RGB(108, 108, 108);
    [headerView addSubview:averageMoneyLbl];
    self.averageMoneyLbl = averageMoneyLbl;
    [averageMoneyLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(totalMoneyLbl.mas_bottom);
        make.left.mas_equalTo(15);
    }];
    
    // chart
    YAYIOALineChart *chartView = [[YAYIOALineChart alloc] initWithFrame:CGRectMake(0, 98, kScreenWidth, 140)];
    chartView.xArray = @[@"1月", @"12月"];
    chartView.chartType = ChartTypeThisYear;
    [headerView addSubview:chartView];
    self.chartView = chartView;
    
    // 线
    UIView *hLineView2 = [[UIView alloc] init];
    hLineView2.backgroundColor = RGB(201, 201, 201);
    [headerView addSubview:hLineView2];
    [hLineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(chartView.mas_bottom);
        make.left.right.mas_equalTo(headerView);
        make.height.mas_equalTo(0.5);
    }];
    
    UILabel *typeTitleLbl = [[UILabel alloc] init];
    typeTitleLbl.text = @"支出排行";
    typeTitleLbl.font = VRFont(14);
    typeTitleLbl.textColor = RGB(108, 108, 108);
    [headerView addSubview:typeTitleLbl];
    self.typeTitleLbl = typeTitleLbl;
    [typeTitleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(hLineView2);
        make.left.mas_equalTo(15);
        make.height.mas_equalTo(32);
    }];
    
    self.tableView.tableHeaderView = headerView;
}


- (void)setupDropMenu
{
    
    //若列表展示内容与按钮展示内容相同则showArr传nil即可。
    XMenuModel *model0 = [[XMenuModel alloc] init];
    model0.name = @"支出";
    model0.imageName = @"ic_expenses";
    
    XMenuModel *model1 = [[XMenuModel alloc] init];
    model1.name = @"收入";
    model1.imageName = @"ic_income";
    NSMutableArray *totalArray = [NSMutableArray array];
    [totalArray addObject:@[model0, model1]];
    
    XDropMenuView *dropMenu = [[XDropMenuView alloc] initWithFrame:CGRectMake(70, 0, SCREEN_WIDTH - 70 * 2, 36) showOnView:self.view AllDataArr:totalArray showArr:[@[@"支出"] mutableCopy]];
    dropMenu.buttonNormalImage = @"pull_down_selector_normal";
    dropMenu.buttonSelectedImage = @"pull_down_selector_normal";
    dropMenu.fonteSize = 18;
    [dropMenu selectClum:0 Row:0];
    dropMenu.delegate = self;
    self.navigationItem.titleView = dropMenu;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [super touchesBegan: touches withEvent:event];
    
}


#pragma mark - getdate
- (void)getData
{
    self.chartModelArray = [[KADataBase sharedDataBase] getModelArrayWithDataType:self.dateType type:self.type];
    self.chartView.dataArray = self.chartModelArray;
    
    self.groupModelArray = [[KADataBase sharedDataBase] getGroupModelArrayWithDataType:self.dateType type:self.type];
    
    // 获取本月天数
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
    NSUInteger numberOfDaysInMonth = range.length;
    // 修改总数
    double totalMoney = ((KAAccountGroupModel *)[self.groupModelArray lastObject]).totalMoney;
    double averageMoney = 0;
    if (self.groupModelArray.count > 0) {
        
        totalMoney = ((KAAccountGroupModel *)[self.groupModelArray firstObject]).totalMoney;
        averageMoney = totalMoney / numberOfDaysInMonth;
    }
    
    NSString *typeStr = self.type == 1 ? @"总收入" : @"总支出";
    self.totalMoneyLbl.text = [NSString stringWithFormat:@"%@：%.2lf", typeStr, totalMoney];
    self.averageMoneyLbl.text = [NSString stringWithFormat:@"平均值：%.2lf", averageMoney];
    
    [self.tableView reloadData];
}

#pragma mark - action
- (void)indexDidChangeForSegmentedControl:(UISegmentedControl *)segement
{
    if (segement.selectedSegmentIndex == 0) {
        
        NSDate *firstDate = [VRCalendarTool dateForFistDayOnWeek:[NSDate date]];
        NSDate *lastDate = [VRCalendarTool dateForLastDayOnWeek:[NSDate date]];
        NSString *firstDateStr = [VRCalendarTool stringWithDate:firstDate formatString:@"MM-dd"];
        NSString *lastDateStr = [VRCalendarTool stringWithDate:lastDate formatString:@"MM-dd"];
        
        self.calendarTypeLbl.text = @"本周";
        self.dateType = DataTypeThisWeek;
        self.chartView.xArray = @[firstDateStr, lastDateStr];
        self.chartView.chartType = ChartTypeThisWeek;
        
    }else if (segement.selectedSegmentIndex == 1){
        
        self.calendarTypeLbl.text = @"本月";
        self.dateType = DataTypeThisMonth;
        // 获取本月天数
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
        NSUInteger numberOfDaysInMonth = range.length;
        
        self.chartView.xArray = @[@"1", [NSString stringWithFormat:@"%ld", (long)numberOfDaysInMonth]];
        self.chartView.chartType = ChartTypeThisMonth;
    }else if (segement.selectedSegmentIndex == 2){
        
        self.calendarTypeLbl.text = @"本年";
        self.dateType = DataTypeThisYear;
        self.chartView.xArray = @[@"1月", @"12月"];
        self.chartView.chartType = ChartTypeThisYear;
    }
    [self getData];
}

- (void)handleNotification:(NSNotification *)notification
{
    [self getData];
}


#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.groupModelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return [UIView new];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    KAAccountGroupModel *groupModel = self.groupModelArray[indexPath.row];
    
    KAChartCell *cell = [KAChartCell cellWith:tableView];
    cell.groupModel = groupModel;
//    if (indexPath.section == 3 - 1 && indexPath.row == 5 - 1) {
//        cell.lineType = LineTypeBottom;
//    }else if (indexPath.row == 5 - 1){
//        cell.lineType = LineTypeCenterAndBottom;
//    }else{
//        cell.lineType = LineTypeCenter;
//    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}


#pragma mark - XDropMenuViewDelegate
- (void)dropMenuView:(XDropMenuView *)dropMenuView didSelectRowAtColum:(NSInteger)colum Row:(NSInteger)row model:(XMenuModel *)model
{
    self.type = row;
    [self getData];
}


@end
